package com.lww.smartbathroom.control;

import com.lww.smartbathroom.model.Result;
import com.lww.smartbathroom.model.Role;
import com.lww.smartbathroom.model.User;
import com.lww.smartbathroom.model.UserLoginInfo;
import com.lww.smartbathroom.param.UserQueryParam;
import com.lww.smartbathroom.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName UserControl
 * @Author 赖伟伟
 * @Date 2020/12/14 16:37
 **/
@Controller
public class UserControl {
    private static final Logger LOG = LoggerFactory.getLogger(UserControl.class);
    @Autowired
    private UserService userService;
    @PostConstruct
    public void init(){
        LOG.info("userControl 启动啦");
        LOG.info("userService 注入啦");
    }

    //注册页
    @GetMapping("/app/sign")
    public String signPage() {
        return "sign";
    }

    //提交注册
    @ResponseBody
    @PostMapping("/app/register")
    public Map registerAction(@RequestBody User regiuser, HttpServletRequest request, HttpServletResponse response) {
        Map returnData = new HashMap();
        // 判断登录名是否已存在
        User regiUser = getUserByLoginName(regiuser.getLoginName());
        if (regiUser != null) {
            returnData.put("result", false);
            returnData.put("message", "login name already exists");
        }
        User user = new User();
        user.setLoginName(regiuser.getLoginName());
        user.setMobile(regiuser.getMobile());
        user.setPassword(regiuser.getPassword());
        user.setSchool(regiuser.getSchool());
        user.setCampusCard(regiuser.getCampusCard());
        user.setSex(regiuser.getSex());
        user.setRole(Role.CUSTOM);
        user.setAmount(0.0);
        user.setIntegral(0);
        User newUser = userService.add(user);
        if (newUser != null && StringUtils.hasText(newUser.getId())) {
            returnData.put("result", true);
            returnData.put("message", "register success");
        } else {
            returnData.put("result", false);
            returnData.put("message", "register failed");
        }
        return returnData;

    }
    @PostMapping("/user/save")
    @ResponseBody
    private Result save(@RequestBody User user){
        Result result = new Result();
        result.setSuccess(true);
        if (user==null){
            result.setSuccess(false);
            result.setMessage("user == null");
            return result;
        }
        if (StringUtils.hasText(user.getId())){
            boolean update = userService.modify(user);
            if (update){
               result.setSuccess(true);
            }else {
                result.setSuccess(false);
                result.setMessage("update faild");
            }

            result.setData(update);
            return result;
        }else {
            User add = userService.add(user);
            result.setData(add);
            return result;
        }

    }


    private User getUserByLoginName(String loginName) {
        User regedUser = null;
        UserQueryParam param = new UserQueryParam();
        param.setLoginName(loginName);
        Page<User> users = userService.list(param);

        // 如果登录名正确，只取第一个，要保证用户名不能重复
        if (users != null && users.getContent() != null && users.getContent().size() > 0) {
            regedUser = users.getContent().get(0);
        }

        return regedUser;
    }
    private User getUserByMobile(String mobile){
        User regedUser = null;
        UserQueryParam param = new UserQueryParam();
        param.setMobile(mobile);
        Page<User> users = userService.list(param);

        // 如果手机号正确，只取第一个，要保证用户名不能重复
        if (users != null && users.getContent() != null && users.getContent().size() > 0) {
            regedUser = users.getContent().get(0);
        }

        return regedUser;
    }

    @GetMapping("/app/login")
    public String loginPage(Model model) {
        return "sign";
    }

    @ResponseBody
    @PostMapping("app/authenticate")
    public Map login(@RequestBody User user, HttpServletRequest request, HttpServletResponse response) {
        Map returnMap = new HashMap();
        User regisUser = null;
        regisUser = getUserByMobile(user.getMobile());
        if (regisUser == null){
            returnMap.put("result",false);
            returnMap.put("message","userName is not correct or don't have this user");
            return returnMap;
        }
        if (regisUser.getPassword().equals(user.getPassword()) ) {
            UserLoginInfo userLoginInfo = new UserLoginInfo();
            userLoginInfo.setUserId(regisUser.getId());
            userLoginInfo.setUserName(regisUser.getLoginName());
            // 取得 HttpSession 对象
            HttpSession session = request.getSession();
            // 写入登录信息
            session.setAttribute("userLoginInfo",userLoginInfo);
            returnMap.put("result", true);
            returnMap.put("message", "login success");
            returnMap.put("user",regisUser);
        }else{
            returnMap.put("result",false);
            returnMap.put("message","username or password not correct");
        }

        return returnMap;
    }

    @GetMapping("/getByUserId")
    public Result getByUserId(@RequestParam("userId")String userId){
        Result result = new Result();
        if (!StringUtils.hasText(userId)){
            result.setMessage("userId is blank");
            return result;
        }
        User user = userService.get(userId);
        result.setData(user);
        result.setSuccess(true);
        result.setMessage("sucess");
        return  result;
    }

    @PostMapping("/user/modify")
    @ResponseBody
    public Result modify(@RequestBody User user){
        System.out.println(user==null);
        System.out.println(user.getLoginName());
        Result result = new Result();
        result.setData(userService.modify(user));
        result.setSuccess(true);
        return result;
    }
    @RequestMapping("/user/del")
    @ResponseBody
    public Result del(@RequestParam("id") String userId){
        Result result = new Result();
        result.setData(userService.delete(userId));
        result.setSuccess(true);
        return result;
    }

    @PostMapping("/user/list")
    @ResponseBody
    public Result list(UserQueryParam userQueryParam){
        Result result = new Result();
        if (userQueryParam == null){
            result.setSuccess(false);
            return result;
        }
        result.setSuccess(true);
        result.setData(userService.list(userQueryParam));
        return  result;
    }
}
